<template>
  <div>
    <Top />
    <section class="bg-green-600 flex-col flex items-center justify-center" style="height: 10vh;text-align: center;">
      <div class="container mx-auto px-4">
        <div class="row">
          <div class="col-md-12 text-center">
            <h2 class="text-4xl font-bold text-white">{{ pageTitle }}</h2>
          </div>
        </div>
      </div>
    </section>

    <div class="bg-white py-16">
      <div class="max-w-4xl mx-auto px-8">
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-8">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-green-600"></div>
          <p class="mt-2 text-gray-600">加载中...</p>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="text-center py-8">
          <p class="text-red-500">{{ error }}</p>
          <button @click="fetchArticles" class="mt-4 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">
            重试
          </button>
        </div>

        <!-- 文章列表 -->
        <div v-else-if="newsItems.length > 0" class="space-y-4">
          <div v-for="(item, index) in newsItems" :key="item.id || index"
               @click="goToDetail(item.id)"
               class="flex justify-between items-center py-4 border-b border-gray-200 hover:bg-gray-50 transition-colors cursor-pointer">
            <h3 class="text-lg text-gray-800 hover:text-blue-600 flex-1 mr-4">{{ item.title }}</h3>
            <span class="text-sm text-gray-400 whitespace-nowrap">{{ item.date }}</span>
          </div>
        </div>

        <!-- 无数据状态 -->
        <div v-else class="text-center py-8">
          <p class="text-gray-500">暂无数据</p>
        </div>

        <!-- 分页 -->
        <div v-if="!loading && !error && newsItems.length > 0 && totalPages > 1" class="flex justify-center items-center mt-8 space-x-2">
          <button
            @click="goToPage(currentPage - 1)"
            :disabled="currentPage <= 1"
            :class="[
              'px-3 py-2 transition-colors',
              currentPage <= 1
                ? 'text-gray-400 cursor-not-allowed'
                : 'text-gray-600 hover:text-gray-800 cursor-pointer'
            ]">
            上一页
          </button>

          <!-- 页码按钮 -->
          <template v-for="page in getPageNumbers()" :key="page">
            <button
              v-if="page !== '...'"
              @click="goToPage(page)"
              :class="[
                'px-3 py-2 transition-colors',
                page === currentPage
                  ? 'bg-green-600 text-white rounded'
                  : 'text-gray-600 hover:text-gray-800'
              ]">
              {{ page }}
            </button>
            <span v-else class="px-3 py-2 text-gray-400">...</span>
          </template>

          <button
            @click="goToPage(currentPage + 1)"
            :disabled="currentPage >= totalPages"
            :class="[
              'px-3 py-2 transition-colors',
              currentPage >= totalPages
                ? 'text-gray-400 cursor-not-allowed'
                : 'text-gray-600 hover:text-gray-800 cursor-pointer'
            ]">
            下一页
          </button>
        </div>

        <!-- 分页信息 -->
        <div v-if="!loading && !error && newsItems.length > 0" class="text-center mt-4 text-sm text-gray-500">
          共 {{ total }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
        </div>
      </div>
    </div>
    <Bottom />
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { articleApi } from '~/public/utils/api'

definePageMeta({
  layout: false
})

const route = useRoute()
const mediaType = route.query.media

// 响应式数据
const newsItems = ref([])
const loading = ref(false)
const error = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const pageTitle = computed(() => {
  switch(mediaType) {
    case 'media':
      return 'Industry News More'
    case 'news':
      return 'Platform Dynamics More'
    default:
      return 'News More'
  }
})

// 根据mediaType确定categoryId
const getCategoryId = () => {
  switch(mediaType) {
    case 'media':
      return 2  // Industry News 对应 categoryId: 2
    case 'news':
      return 1  // Platform Dynamics 对应 categoryId: 1 (Latest Insights)
    default:
      return 1
  }
}

// 获取文章列表数据
const fetchArticles = async () => {
  loading.value = true
  error.value = ''

  try {
    const categoryId = getCategoryId()
    const result = await articleApi.getList({
      pageSize: pageSize.value,
      pageNum: currentPage.value,
      categoryId
    })

    // 检查返回状态码
    if (result?.code === 401) {
      navigateTo('/login')
      return
    }

    // 检查其他错误状态码
    if (result?.code && result.code !== 200 && result.code !== 0) {
      const errorMsg = result?.msg || result?.message || `请求失败，错误码: ${result.code}`
      error.value = errorMsg
      console.error('API错误:', errorMsg)
      return
    }

    const rows = result?.rows || result?.data?.rows || []
    total.value = result?.total || result?.data?.total || 0

    // 转换数据格式
    newsItems.value = rows.map((row) => ({
      id: row.id || row.articleId,
      title: row.title || '',
      date: row.createTime || row.publishTime || row.date || '',
      summary: row.summary || row.description || ''
    }))

  } catch (error) {
    console.error('获取数据失败:', error)
    // 检查错误响应中的状态码
    if (error?.response?.status === 401 || error?.code === 401) {
      navigateTo('/login')
      return
    }

    // 设置错误信息
    const errorMsg = error?.response?.data?.msg || error?.message || '网络请求失败，请稍后重试'
    error.value = errorMsg
  } finally {
    loading.value = false
  }
}

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 翻页功能
const goToPage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  fetchArticles()
}

// 点击文章跳转到详情页
const goToDetail = (id) => {
  if (id) {
    navigateTo(`/article/${id}`)
  }
}

// 生成分页页码数组
const getPageNumbers = () => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value

  if (total <= 7) {
    // 如果总页数小于等于7，显示所有页码
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 总是显示第一页
    pages.push(1)

    if (current <= 4) {
      // 当前页在前面时
      for (let i = 2; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      // 当前页在后面时
      pages.push('...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间时
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }

  return pages
}

// 组件挂载时获取数据
onMounted(() => {
  fetchArticles()
})
</script>